package com.ckm.config.xss;

import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 重写wrapper,只能对提交方式为x-www-form-urlencoded和form-data做特殊字符转换,不能对提交方式为json的数据格式做转换
 */
@Slf4j
public class XSSHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XSSHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        return StringEscapeUtils.escapeHtml4(super.getHeader(name));
    }

    @Override
    public String getQueryString() {
        return StringEscapeUtils.escapeHtml4(super.getQueryString());
    }

    @Override
    public String getParameter(String name) {
        return StringEscapeUtils.escapeHtml4(super.getParameter(name));
    }

    public ServletInputStream getInputStream() throws IOException {
        return super.getInputStream();
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameterValues = super.getParameterValues(name);
        if (Objects.isNull(parameterValues)) {
            return null;
        }
        for (int i = 0; i < parameterValues.length; i++) {
            parameterValues[i] = StringEscapeUtils.escapeHtml4(parameterValues[i]);
        }
        return parameterValues;
    }
}
